package apof.dao.datapool
{
	import apof.model.*;
	import apof.dao.DataAccessInterface;

	public class DataPool implements DataAccessInterface
	{
		private var objPools:Object;
		public static var classList:Array=[ConsumeType,Account,User,Transection,Filter,StructureItem,ConsumeLevel,IncomeLevel,Structure,BudgetStc,BudgetItem];
		
		public function init(callback:Function):void {
			ObjPool.dp=this;
			objPools=new Object();
			var unfinished:int=classList.length;
			for each(var clazz:Object in classList) {
				clazz.onInit();
			}
			for each(var clazz2:Object in classList) {
				objPools[clazz2.classInfo.classname]=new ObjPool(clazz2 as Class,function():void{
					if(--unfinished == 0) {
						init_2(callback);
					}
				});
			}
		}
		
		private function init_2(callback:Function):void {
			for each(var op:ObjPool in objPools) {
				op.link();
			}
				
			if(callback!=null)callback();
		}
		
		public function create(target:ApofModel):void
		{
			objPools[target.classInfo.classname].create(target);
		}
		
		public function createWithID(target:ApofModel) :void {
			objPools[target.classInfo.classname].createWithID(target);
		}
		
		public function update(target:ApofModel):void
		{
			objPools[target.classInfo.classname].update(target);
		}
		
		public function updateRef(target:ApofModel,fkName:String ,value:int):void{
			objPools[target.classInfo.classname].updateRef(target,fkName,value);
		}
		
		public function remove(target:ApofModel):void
		{
			objPools[target.classInfo.classname].removeById(target[target.classInfo.primaryKey]);
		}
		
		public function removeById(clazz:Class , id:int):void {
			objPools[clazz.classInfo.classname].removeById(id);
		}
		
		public function retrive(clazz:Class, id:int):ApofModel
		{
			
			return objPools[clazz.classInfo.classname].pk[id];
		}
		
		public function retriveAll(clazz:Class, fkName:String=null, value:Object=null, filter:Function=null, orderBy:String=null, dec:Boolean=false, limit:int=-1):Array
		{
			var range:Array;
			if(fkName==null) range=objPools[clazz.classInfo.classname].all;
			else range=objPools[clazz.classInfo.classname].fk[fkName][value];
			if(range==null)return new Array();
			var result:Array=(filter!=null)?range.filter(filter):range;
			result=result.sortOn(orderBy);
			if(dec)result=result.reverse();
			if(limit>=0)
				result=result.splice(0,limit);
			return result;
		}
		
		
		
	}
}